<template >
    <a-modal v-model:open="openModel" width="1000px" :title="modelTitle" @ok="onFinish" ok-text="提交" cancel-text="取消">
<!--        编辑表单-->
        <a-form
                :model="labBorrowFormState"
                v-bind="layout"
                name="nest-messages">

            <a-form-item v-for="{key,title,inputType,selectList} in modelFormFields" :key="key" :name="[key]" :label="title"  >
                <template v-if="inputType === 'input'">
                    <a-input v-model:value="labBorrowFormState[key]" />
                </template>
                <template v-else-if="inputType === 'input'">
                    <a-input v-model:value="labBorrowFormState[key]" />
                </template>
                <template v-else-if="inputType === 'input-number'">
                    <a-input-number v-model:value="labBorrowFormState[key]" />
                </template>
                <template v-else-if="inputType === 'textarea'">
                    <a-textarea v-model:value="labBorrowFormState[key]" />
                </template>
                <template v-else-if="inputType === 'select'">
                    <a-select
                        placeholder="请选择"
                        v-model:value="labBorrowFormState[key]"
                        style="width: 200px"
                    >
                        <a-select-option v-for="{selectKey,selectName} in selectList"
                                         :value="selectKey"
                                         :key="selectKey">
                            {{ selectName }}
                        </a-select-option>
                    </a-select>
                </template>
            </a-form-item>
        </a-form>
<!--        显示的labId-->
            <div style="align-content:center;font-size: 14px;background-color: #e6f7ff;padding:8px 15px;border-radius:4px;border:1px solid #91d5ff;height: 38px">
                <a-button type="link" @click="loadModelLabDataSource">列出所有可用的实验室</a-button>
                <span>当前选择的申请实验室编号：</span>
                <span>{{ labBorrowFormState['labNumber'] || '未选择实验室' }}</span>
            </div>
<!--        展示的数据表单-->
        <a-table  v-model:dataSource="modelLabDataSource" :columns="modelLabColumns">
            <template #bodyCell="{ column, record }">
                <!--        操作列-->
                <template v-if="column.key==='action'">
                    <a-button @click="chooseLabTo(record)">选择该实验室</a-button>
                </template>
            </template>
        </a-table>
    </a-modal>
</template>
<script lang="ts" setup>

//控制里面的表单
import {computed, onMounted, reactive} from "vue";
import {modelFormFields} from './labBorrowAdd.data'
import {$getLabTypeList, $getSectionList, $getSemesterList, $getWeekdayList} from "@/api/loadDictList";
import {message} from "ant-design-vue";
import {$addLabBorrow, $editLabBorrow, $getAvaLabBorrow} from "@/views/labBorrow/add/labBorrowAdd.api";
//空闲实验室的表单
const modelLabDataSource=defineModel("modelLabDataSource")
//提交的数据，并且可能是编辑的数据
const labBorrowFormState = defineModel("labBorrowFormState");


//控制开关Model
const openModel = defineModel('openModel')
//如果编辑=1，如果是新增，这个值为0
const ModelRoleEditId=defineModel("modelRoleEditId")
//提交请求成功后的回调函数
const emit = defineEmits(['submitSuccess'])

//弹窗的标题
const modelTitle = computed(() => {
    switch (ModelRoleEditId.value) {
        case "0":
        case 0:return "新增申请信息";
        case "1":
        case 1:return "编辑申请信息";
        default:
            return "信息"
    }

});

//样式
const layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 16 },
};

/**
 * 提交数据
 */
const onFinish = async () => {
    if(ModelRoleEditId.value == "0"){
        //新增
        console.log("labBorrowFormState",labBorrowFormState.value)
        //进行非空校验
        const {labId,labType,reason,sectionId,week,weekday} = labBorrowFormState.value
        if(labId==null||labType==null||sectionId==null||week==null||weekday==null){//除了season其他都要检查
            message.error("缺少必要数据项")
            return
        }//发送请求
        try{
            const {code,message:resultMessage,data}= await $addLabBorrow(labBorrowFormState.value,{})
            if(code==200){
                message.success(data)
                emit('submitSuccess');
                openModel.value=false
            }else{
                message.error(resultMessage)
            }
        }catch (e){
            message.error("新增失败")
        }
    }else{
        //编辑
        console.log("EditLabBorrowFormState",labBorrowFormState.value)
        //进行非空校验
        const {labId,labType,reason,sectionId,week,weekday} = labBorrowFormState.value
        if(labId==null||labType==null||sectionId==null||week==null||weekday==null){//除了season其他都要检查
            message.error("缺少必要数据项")
            return
        }//发送请求
        try{
            const {code,message:resultMessage,data}= await $editLabBorrow(labBorrowFormState.value,{})
            if(code==200){
                message.success(data)
                emit('submitSuccess')
                openModel.value=false
            }else{
                message.error(resultMessage)
            }
        }catch (e){
            message.error("编辑错误")
        }
    }
}
const loadSelectListData =async()=>{

    //获取信息
    let semesterList = await $getSemesterList();
    let weekdayList = await $getWeekdayList();
    let sectionList = await $getSectionList();
    let labTypeList = await $getLabTypeList();
    console.log("semesterList")
    modelFormFields.forEach((fieldItem: any) => {
        if (fieldItem.key == "semesterId") {
            fieldItem.selectList.length=0
            //将后端获取的semesterList放入formFields
            semesterList.forEach((semesterItem: any) => {
                const {id: selectKey, semesterName: selectName} = semesterItem
                const newSemesterItem = {selectKey: selectKey, selectName: selectName}
                fieldItem.selectList.push(newSemesterItem)
            })
        }
        if (fieldItem.key == "labType") {
            fieldItem.selectList.length=0
            //将后端获取的semesterList放入formFields
            labTypeList.forEach((labTypeItem: any) => {
                const {id: selectKey, labTypeName: selectName} = labTypeItem
                const newSemesterItem = {selectKey: selectKey, selectName: selectName}
                fieldItem.selectList.push(newSemesterItem)
            })
        }
        if (fieldItem.key == "sectionId") {
            fieldItem.selectList.length=0
            //将后端获取的semesterList放入formFields
            sectionList.forEach((sectionItem: any) => {
                const {id: selectKey, sectionName: selectName} = sectionItem
                const newSemesterItem = {selectKey: selectKey, selectName: selectName}
                fieldItem.selectList.push(newSemesterItem)
            })
        }
        if (fieldItem.key == "weekday") {
            fieldItem.selectList.length=0
            //将后端获取的semesterList放入formFields
            weekdayList.forEach((weekdayItem: any) => {
                const {id: selectKey, weekdayName: selectName} = weekdayItem
                const newSemesterItem = {selectKey: selectKey, selectName: selectName}
                fieldItem.selectList.push(newSemesterItem)
            })
        }
    })

}

//**********************************显示的实验室的表格******************
const modelLabColumns=
    [
        {
            title:'实验室',
            key:'labNumber',
            dataIndex:'labNumber',
        },
        {
            title:'设备数量',
            key:'equipmentCount',
            dataIndex:'equipmentCount',
        },
        {
            title: '操作',
            key: 'action',
        }
    ]
const loadModelLabDataSource = async ()=>{
    console.log(modelLabDataSource)
    //配置数据项，空闲数据列
    //发送数据，并且请求要求返回list集合
    console.log("申请前labBorrowFormState",labBorrowFormState.value)
    try{
        const {code,message:labResultMessage,data} = await $getAvaLabBorrow(labBorrowFormState.value,{})
        console.log(code,message,data)
        if(code==200){
            modelLabDataSource.value.length=0
            data.forEach((labItem)=>{
                modelLabDataSource.value.push(labItem)
            })
        }else {
            message.error(labResultMessage)
        }
    }catch(error){
        console.log(error);
        message.error("获取空闲数据列失败")
    }
}
/**
 * 选择实验室
 */
const chooseLabTo = (record)=>{
    console.log(record);
    console.log(labBorrowFormState.value);
    labBorrowFormState.value.labId = record.id
    labBorrowFormState.value.labNumber = record.labNumber

}
//**********************************
onMounted(async ()=>{
    //加载页面动态加载项目,这些一般不会变更
    await loadSelectListData()
})

</script>